package com.ruoyi.web.controller.wechatApplet;

import com.ruoyi.background.domain.*;
import com.ruoyi.background.service.*;
import com.ruoyi.background.utils.CONFIG_KEY;
import com.ruoyi.background.utils.REDIS_KEY;
import com.ruoyi.background.utils.SYS_CONSTANT;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 积分接口
 */
@RestController
@RequestMapping("/wechat/grade")
public class WechatGradeController extends BaseController {

    @Autowired
    private IAppGradeRecordService appGradeRecordService;

    @Autowired
    private IAppRankUserService appRankUserService;

    @Autowired
    private IAppWechatStepService wechatStepService;

    @Autowired
    private IAppRankDeptService appRankDeptService;

    @Autowired
    private IAppLotteryPrizeService appLotteryPrizeService;

    @Autowired
    private IAppLotteryRecordService appLotteryRecordService;

    @Autowired
    private IAppGradeLevelService gradeLevelService;

    @Autowired
    private IAppRankTeamService teamRankService;

    @Autowired
    private IAppWorkTeamService workTeamService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 获取用户的积分记录
     *
     * @param record 查询条件
     * @return 结果
     */
    @GetMapping("/getUserGrade")
    public TableDataInfo getUserGradeList(AppGradeRecord record) {
        startPage();
        record.setUserId(SecurityUtils.getUserId());
        List<AppGradeRecord> list = appGradeRecordService.selectAppGradeRecordList(record);
        return getDataTable(list);
    }

    /**
     * 查询排行榜
     *
     * @param appRankUser 查询参数
     * @param type        0个人榜 1今日榜 2队伍榜
     * @return list
     */
    @GetMapping("/getUserRank/{type}")
    public TableDataInfo getUserRank(AppRankUser appRankUser, @PathVariable Integer type) {
        List<AppRankUser> rankUserList = new ArrayList<>();
        startPage();
        if (type == 0) {
            rankUserList = appRankUserService.selectAppRankUserList(appRankUser);
        } else if (type == 1) {
            rankUserList = wechatStepService.getTodayExchangeStep();
        } else if (type == 2) {
            rankUserList = appRankDeptService.getDeptRankList(appRankUser);
        } else if (type == 3) {
            rankUserList = teamRankService.getTeamRankList(appRankUser);
            for (AppRankUser rankUser : rankUserList) {
                rankUser.setDeptName(rankUser.getTeamName());
                rankUser.setDeptId(rankUser.getTeamId());
            }
        }
        return getDataTable(rankUserList);
    }

    /**
     * 获取用户的排名
     *
     * @param type 0个人榜排名 1今日榜排名 2部门榜排名 3队伍排名
     */
    @GetMapping("getUserRankIndex/{type}")
    public AjaxResult getUserRankIndex(@PathVariable Integer type) {
        //获取总排名
        AppRankUser appRankUser = appRankUserService.selectAppRankUserByUserId(SecurityUtils.getUserId());
        String totalRank = ObjectUtils.isEmpty(appRankUser) ? "-" : String.valueOf(appRankUser.getRank());
        //获取今日排名
        Long res = wechatStepService.getUserTodayRank();
        String todayRank = ObjectUtils.isEmpty(res) || res == 9999L ? "-" : String.valueOf(res);
        //获取部门排名
        AppRankDept appRankDept = appRankDeptService.selectAppRankDeptByUserDeptId(SecurityUtils.getDeptId());
        String deptRank = ObjectUtils.isEmpty(appRankDept) ? "-" : String.valueOf(appRankDept.getRank());
        //获取队伍排名
        String teamRank;
        AppWorkTeamUser team = workTeamService.getUserTeamInfo();
        if (ObjectUtils.isEmpty(team)) teamRank = "-";
        else {
            AppRankTeam appRankTeam = teamRankService.selectAppRankByTeamId(team.getTeamId());
            teamRank = ObjectUtils.isEmpty(appRankTeam) ? "-" : String.valueOf(appRankTeam.getRank());
        }
        Map<String, String> rank = new HashMap<>();
        rank.put("totalRank", totalRank);
        rank.put("todayRank", todayRank);
        rank.put("deptRank", deptRank);
        rank.put("teamRank", teamRank);
        return AjaxResult.success(rank);
    }


    /**
     * 获取奖品的列表
     *
     * @return 结果
     */
    @GetMapping("/getPriseList")
    public AjaxResult getPriseList() {
//        String key = REDIS_KEY.PRIZE_ALL_LIST_KEY;
//        List<AppLotteryPrize> prizeList = redisCache.getCacheList(key);
//        if (ObjectUtils.isEmpty(prizeList)) {
//            // 换成 json 直接 写死
//            AppLotteryPrize query = new AppLotteryPrize();
//            query.setStatus(0);
//            prizeList = appLotteryPrizeService.selectAppLotteryPrizeList(query);
//            redisCache.deleteByKey(key);
//            redisCache.setCacheList(key, prizeList);
//            redisCache.expire(key, 60 * 48, TimeUnit.MINUTES);
//        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("data", SYS_CONSTANT.PRIZE_LIST_CONS);
        String nowWinNumKey = REDIS_KEY.APP_LOTTERY_WINNING_NUM;
        Integer nowWinNum = redisCache.getCacheObject(nowWinNumKey); //当前中奖的数量
        nowWinNum = nowWinNum == null ? 0 : nowWinNum;
        int prizeMaxMum = 566;
        int s = prizeMaxMum - nowWinNum;
        ajaxResult.put("number", s);
        return ajaxResult;
    }

    /**
     * 用户积分抽奖
     *
     * @return 中奖奖品
     */
    @GetMapping("/userLottery")
    @RepeatSubmit(interval = 10000, message = "您已抽奖，请10秒后再试！")
    public AjaxResult userLottery() {
        AppLotteryPrize prize = appLotteryPrizeService.lotteryPrize();
        return AjaxResult.success(prize);
    }

    /**
     * 查询中奖列表
     *
     * @param record 查询条件
     * @return 结果
     */
    @GetMapping("/getLotteryRecord")
    public TableDataInfo getLotteryRecord(AppLotteryRecord record) {
        startPage();
        record.setUserId(SecurityUtils.getUserId());
        List<AppLotteryRecord> records = appLotteryRecordService.selectAppLotteryRecordList(record);
        return getDataTable(records);
    }

    /**
     * 获取积分等级
     *
     * @return 结果
     */
    @GetMapping("/getUserGradeLevel")
    public AjaxResult getUserGradeLevel() {
        AjaxResult ajaxResult = AjaxResult.success();
        Integer userCountInGrade = appGradeRecordService.getUserCountInGrade();
        AppGradeLevel nextAppGradeLevel = gradeLevelService.getNextAppGradeLevel(userCountInGrade);
        AppGradeLevel beforeAppGradeLevel = gradeLevelService.getBeforeAppGradeLevel(userCountInGrade);
        ajaxResult.put("nextLevel", nextAppGradeLevel);
        ajaxResult.put("before", beforeAppGradeLevel);
        return ajaxResult;
    }

    /**
     * 获取最新中奖数据 不需要分页 获取最新的 20个
     *
     * @return list
     */
    @GetMapping("/getNewUserPrizeList")
    public AjaxResult getNewUserPrizeList() {
        String key = REDIS_KEY.PRIZE_WINNING_USER_LIST_KEY;
        List<AppLotteryRecord> records = redisCache.getCacheList(key);
        if (ObjectUtils.isEmpty(records)) {
            startPage();
            records = appLotteryRecordService.selectAppLotteryRecordList(new AppLotteryRecord());
            if (ObjectUtils.isEmpty(records))
                records = new ArrayList<>();
            for (AppLotteryRecord record : records) {
                record.setPhonenumber(StringUtils.hide(record.getPhonenumber(), 3, 7));
            }
            redisCache.deleteByKey(key);
            redisCache.setCacheList(key, records);
            redisCache.expire(key, 60 , TimeUnit.MINUTES);
        }
        return AjaxResult.success(records);
    }


    /**
     * 获取奖品的数量
     *
     * @return
     */
    @GetMapping("/getPrizeNumber")
    public AjaxResult getPrizeNumber() {
        String nowWinNumKey = REDIS_KEY.APP_LOTTERY_WINNING_NUM;
        Integer nowWinNum = redisCache.getCacheObject(nowWinNumKey); //当前中奖的数量
        nowWinNum = nowWinNum == null ? 0 : nowWinNum;
        int prizeMaxMum = Integer.parseInt(sysConfigService.selectConfigByKey(CONFIG_KEY.LOTTERY_WIM_MAX_NUMBER));
        int s = prizeMaxMum - nowWinNum;
        return AjaxResult.success(s);
    }


}
